package com.taiyuan.tongcheng.ui;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.utils.FileUtils;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.taiyuan.tongcheng.application.AppConfig;
import com.taiyuan.tongcheng.bean.UpdateInfo;
import com.taiyuan.tongcheng.http.HTTPFieldConstant;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.CommonUtil;
import com.taiyuan.tongcheng.util.DialogUtil;
import com.taiyuan.tongcheng.util.TcUtil;
import com.taiyuan.tongcheng.widget.ProgressWheel;
import com.taiyuan.tongcheng.widget.dialog.TcBuilder;
import com.tytc56.user.R;

public class SettingActivity extends BaseActivity {

	public static final int SHOW_PROGRESS = 0;
	private KJHttp kjhttp;
	// widget
	@BindView(id = R.id.rl_app_update, click = true)
	private RelativeLayout appupdateRl;
	@BindView(id = R.id.tv_app_version)
	private TextView appVersonTv;

	// 下载显示控件
	private TextView processMes;
	private TextView processAll;
	private TextView processInfo;
	private Button cancelBtn;
	private int updateCount = 0;
	private TcBuilder tcInformDialog;

	// 当前下载进度
	private long totalsize;
	private long currentsize;
	private Dialog dialog;
	private int progress;
	private Dialog loaddingDialog;
	private UpdateInfo appInfo;
	private ProgressWheel progressBar;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_setting);
	}

	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		initDownloadDialog(SettingActivity.this);
		loaddingDialog = DialogUtil.getLoginDialog(this);
		topTv.setText("设置");
		rightTv.setVisibility(View.GONE);
		appVersonTv.setText("V"
				+ SystemTool.getAppVersionName(getApplicationContext()));
		tcInformDialog = TcBuilder.getInstance(this, 1);
	}

	private Handler tcHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SHOW_PROGRESS:

				if (currentsize > 0) {
					processMes.setText(msg.arg1 + "%");
					processAll.setText(currentsize + "/" + totalsize + "M");
				}
				break;

			default:
				break;
			}
		}

	};

	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.rl_app_update:
			if (checkNet()) {
				update();
			}
			break;

		default:
			break;
		}
	}

	private boolean checkNet() {
		if (SystemTool.checkNet(getApplicationContext())) {
			return true;
		} else {
			return false;

		}
	}

	@Override
	public void initData() {
		super.initData();
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		config.MAX_DOWNLOAD_TASK_SIZE = 2;
		kjhttp = new KJHttp(config);

	}

	/**
	 * 
	 * @Description: TODO
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-9-22 下午6:59:53
	 * @update (date)
	 */
	private void update() {
		TcLoaddingDialog.show();
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjhttp = new KJHttp(config);
		HttpParams params = new HttpParams();
		params.put(HTTPFieldConstant.POST_PARAMS_COMMON_ACT,
				TcUtil.getApiName(TcWebservice.API.APP_UPDATA));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_ROLE, 1);
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_FROM, "1");
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_DEVID,
				CommonUtil.getAndroidDeviceUnique(this));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_VER,
				SystemTool.getAppVersionCode(this));

		kjhttp.post(TcWebservice.WEBSERVER_IP + TcWebservice.API.APP_UPDATA,
				params, new HttpCallBack() {
					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);

					}

					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							String webdateString = URLDecoder
									.decode(t, "UTF-8");
							KJLoger.debug(webdateString);
							WebData data = TcJsParser
									.getWedataData(webdateString);
							if (data.getStatus() == 1) {
								UpdateInfo appInfo = JSON.parseObject(
										data.getData(), UpdateInfo.class);
								KJLoger.debug(appInfo.toString());
								JSONObject obj = new JSONObject(data.getData());
								int a = obj.optInt("vCode", 1);
								if (a > SystemTool
										.getAppVersionCode(getApplicationContext())) {
									showAppUpdataDialog(appInfo);
								}else{
									showCustomToast("已是最新版本");
								}
								// showAppUpdataDialog(appInfo);
								// download("http://git.oschina.net/reliables/Tcps/raw/master/TongCheng.apk");
							} else {
								showErroCustomToast(data.getMsg());
							}

							if (TcLoaddingDialog != null
									&& TcLoaddingDialog.isShowing()) {
								TcLoaddingDialog.dismiss();
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

				});
	}

	/**/

	private void showAppUpdataDialog(final UpdateInfo appInfo) {

		StringBuilder bulder = new StringBuilder();
		String[] updataContent = {};
		if (!StringUtils.isEmpty(appInfo.getUpdateLog())) {
			List<String> upString = JSON.parseArray(appInfo.getUpdateLog(),
					String.class);
			for (int i = 0; i < upString.size(); i++) {
				bulder.append(upString.get(i));
			}
		}

		tcInformDialog.withTitle("同成配送V" + appInfo.getVer())
				.withButton1Text("暂不升级").withContent(bulder.toString())
				.withButton2Text("立刻升级").setButton1Click(new OnClickListener() {

					@Override
					public void onClick(View v) {
						tcInformDialog.cancel();
					}
				}).setButton2Click(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.show();
						download(appInfo.getUrl());
						tcInformDialog.cancel();
					}
				});
		tcInformDialog.show();

	}

	private void download(String url) {

		// loaddingDialog.show();
		final File folder = FileUtils.getSaveFolder(AppConfig.saveFolder);
		File tempFile = new File(folder + "/tcps.apk.tmp");
		if (tempFile.exists()) {
			tempFile.delete();
		}
		kjhttp.download(folder + File.separator + AppConfig.ApkName, url,
				new HttpCallBack() {

					/**
					 * 下载过程
					 */
					@Override
					public void onLoading(long count, long current) {
						super.onLoading(count, current);
						KJLoger.debug("count=" + count + "=current=" + current);
						totalsize = count;
						currentsize = current;
						if (updateCount == 0
								|| (current * 100 / count - 3) >= updateCount) {
							updateCount += 3;
							Message msg = new Message();
							msg.obtain();
							msg.what = SHOW_PROGRESS;
							msg.arg1 = updateCount;
							tcHandler.sendMessage(msg);

						}

					}

					/**
					 * 下载完成，开始安装
					 */
					@Override
					public void onSuccess(byte[] t) {
						super.onSuccess(t);
						// loaddingDialog.dismiss();
						dialog.cancel();
						SystemTool.installApk(getApplicationContext(),
								new File(folder + File.separator
										+ AppConfig.ApkName));
					}
				});
	}

	/**
	 * 
	 * @Description: 初始化下载弹框
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-9-23 下午4:49:39
	 * @update (date)
	 */
	private void initDownloadDialog(Context context) {
		dialog = new Dialog(SettingActivity.this, R.style.dialog_tran);
		dialog.setCanceledOnTouchOutside(false);
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View vi = inflater.inflate(R.layout.layout_download_dialog, null);
		processMes = (TextView) vi.findViewById(R.id.process_msg);
		processAll = (TextView) vi.findViewById(R.id.process_all);
		cancelBtn = (Button) vi.findViewById(R.id.btn_inform_cancel);
		progressBar = (ProgressWheel) vi.findViewById(R.id.progress_wheel);
		cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				kjhttp.cancelAll();
			}
		});
		dialog.setContentView(vi);
	}

}
